<?php

session_start();
include_once '../include/common.php';
require_once '../include/Classes/PHPExcel.php';
$core = new core();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli') {
    echo json_encode(array('type' => 1, 'msg' => "Có lỗi xảy ra, vui lòng thử lại."));
    die;
}
$zen_order_id = isset($_POST["zen_order_id"]) ? intval($_POST["zen_order_id"]) : 0;
$by_product_customer = isset($_POST["by_product_customer"]) ? intval($_POST["by_product_customer"]) : 0;
$by_order_status = isset($_POST["by_order_status"]) ? intval($_POST["by_order_status"]) : 0;
$by_province = isset($_POST["by_province"]) ? intval($_POST["by_province"]) : 0;
$by_payment = isset($_POST["by_payment"]) ? intval($_POST["by_payment"]) : 0;
$search_text = isset($_POST["search_text"]) ? addslashes(trim($_POST["search_text"])) : '';
$start_time = isset($_POST["start_time"]) ? addslashes(trim($_POST["start_time"])) : '';
$end_time = isset($_POST["end_time"]) ? addslashes(trim($_POST["end_time"])) : '';
$hidden_group_1 = isset($_POST["hidden_group_1"]) ? intval($_POST["hidden_group_1"]) : 0;
$hidden_group_2 = isset($_POST["hidden_group_2"]) ? intval($_POST["hidden_group_2"]) : 0;
$hidden_group_3 = isset($_POST["hidden_group_3"]) ? intval($_POST["hidden_group_3"]) : 0;
$hidden_group_4 = isset($_POST["hidden_group_4"]) ? intval($_POST["hidden_group_4"]) : 0;
$order_by = '';
if ($by_product_customer == 0 && $by_order_status == 0 && $by_province == 0 && $by_payment == 0 && $search_text != "") {
    echo json_encode(array('type' => 1, 'msg' => "Vui lòng chọn 1 trong 4 sự lựa chọn để sắp xếp!"));
    die;
}
if ($start_time != "" && $end_time != "") {
    if (strtotime($end_time) <= strtotime($start_time)) {
        echo json_encode(array('type' => 1, 'msg' => "Bạn phải chọn thời gian kết thúc lớn hơn thời gian bắt đầu!"));
        die;
    }
}
$old_start_time = '';
$old_end_time = '';
if ($start_time != "") {
    $old_start_time = date("d-m-Y H:i:s", strtotime($start_time));
    $start_time = $core->changeDateMysqlToCompare(date("Y-m-d H:i:s", strtotime($start_time)));
}
if ($end_time != "") {
    $old_end_time = date("d-m-Y H:i:s", strtotime($end_time));
    $end_time = $core->changeDateMysqlToCompare(date("Y-m-d H:i:s", strtotime($end_time)));
}

$where = '';
if ($by_order_status > 0) {
    switch ($by_order_status) {
        case 1:
            //store
            $where.='order_status=0';
            if ($start_time != "") {
                $where.=' AND store_date >="' . $start_time . '"';
            }
            if ($end_time != "") {
                $where.=' AND store_date<"' . $end_time . '"';
            }
            $order_by .= "store_date asc";
            break;
        case 2:
            //online
            $where.='order_status=1';
            if ($start_time != "") {
                $where.=' AND online_date >="' . $start_time . '"';
            }
            if ($end_time != "") {
                $where.=' AND online_date<"' . $end_time . '"';
            }
            $order_by .= "online_date asc";
            break;
        case 3:
            //hàng có sẵn
            $where.='order_status=2';
            break;
        case 4:
            //đã nhận hàng
            $where.='order_status=3';
            if ($start_time != "") {
                $where.=' AND received_date >="' . $start_time . '"';
            }
            if ($end_time != "") {
                $where.=' AND received_date<"' . $end_time . '"';
            }
            $order_by .= "received_date asc";
            break;
        case 5:
            //đang shipping
            $where.='order_status=4';
            break;
        case 6:
            //khách đã nhận
            $where.='order_status=5';
            if ($start_time != "") {
                $where.=' AND saled_date >="' . $start_time . '"';
            }
            if ($end_time != "") {
                $where.=' AND saled_date<"' . $end_time . '"';
            }
            $order_by .= "saled_date asc";
            break;
        case 7:
            //hết hàng
            $where.='order_status=6';
            break;
        case 8:
            //ORDER
            $where.='order_status=7';
            if ($start_time != "") {
                $where.=' AND customer_order_date >="' . $start_time . '"';
            }
            if ($end_time != "") {
                $where.=' AND customer_order_date <"' . $end_time . '"';
            }
            $order_by .= "customer_order_date asc";
            break;
        case 9:
            //chưa chắc chắn
            $where.='order_status=8';
            break;
    }
} else {
    if ($start_time != "") {
        if ($where == '') {
            $where.='(store_date >="' . $start_time . '" OR online_date >="' . $start_time . '" OR received_date >="' . $start_time . '"
            OR saled_date >="' . $start_time . '" OR customer_order_date >="' . $start_time . '")';
        } else {
            $where.=' AND (store_date >="' . $start_time . '" OR online_date >="' . $start_time . '" OR received_date >="' . $start_time . '"
            OR saled_date >="' . $start_time . '" OR customer_order_date >="' . $start_time . '")';
        }
    }
    if ($end_time != "") {
        if ($where == '') {
            $where.='(store_date<"' . $end_time . '" OR online_date<"' . $end_time . '" OR received_date<"' . $end_time . '" 
                  OR saled_date<"' . $end_time . '" OR customer_order_date <"' . $end_time . '")';
        } else {
            $where.=' AND (store_date<"' . $end_time . '" OR online_date<"' . $end_time . '" OR received_date<"' . $end_time . '" 
                  OR saled_date<"' . $end_time . '" OR customer_order_date <"' . $end_time . '")';
        }
    }
}
if ($order_by != "") {
    //ORDER: sắp xếp ngày đặt mua tăng dần
    if ($by_product_customer == 1) {
        $order_by .= ", product_code asc";
    } elseif ($by_product_customer == 2) {
        $order_by .= ", facebook_name asc";
    }
} else {
    if ($by_product_customer == 1) {
        $order_by .= "product_code asc";
    } elseif ($by_product_customer == 2) {
        $order_by .= "facebook_name asc";
    }
}
if ($by_payment > 0) {
    switch ($by_payment) {
        case 1:
            //thanh toán hết
            if ($where == '') {
                $where.='total_current_money=0';
            } else {
                $where.=' AND total_current_money=0';
            }
            break;
        case 2:
            //thanh toán thừa
            if ($where == '') {
                $where.='total_current_money > 0';
            } else {
                $where.=' AND total_current_money > 0';
            }
            break;
        case 3:
            //thanh toán thiếu
            if ($where == '') {
                $where.='total_current_money < 0';
            } else {
                $where.=' AND total_current_money < 0';
            }
            break;
        case 4:
            //đã cọc
            if ($where == '') {
                $where.='total_payment > 0';
            } else {
                $where.=' AND total_payment > 0';
            }
            break;
        case 5:
            //chưa thanh toán
            if ($where == '') {
                $where.='total_payment = 0';
            } else {
                $where.=' AND total_payment = 0';
            }
            break;
    }
}
if ($search_text !== "") {
    if ($by_product_customer == 1) {
        if ($where == '') {
            $where.="product_code LIKE '%" . $search_text . "%'";
        } else {
            $where.=" AND product_code LIKE '%" . $search_text . "%'";
        }
    } elseif ($by_product_customer == 2) {
        if ($where == '') {
            $where.="facebook_name LIKE '%" . $search_text . "%'";
        } else {
            $where.=" AND facebook_name LIKE '%" . $search_text . "%'";
        }
    }
}
if ($by_province > 0) {
    switch ($by_province) {
        case 1:
            //tỉnh
            if ($where == '') {
                $where.='province=1';
            } else {
                $where.=' AND province=1';
            }
            break;
        case 2:
            //Hà Nội
            if ($where == '') {
                $where.='province=0';
            } else {
                $where.=' AND province=0';
            }
            break;
    }
}
$zen_order = $core->checkZenOrderByID($zen_order_id);
if ($zen_order) {
    $total_result = array();
    if ($by_order_status > 0 || $by_product_customer == 1) {
        $is_group_customer = 0;
    } else {
        $is_group_customer = 1;
    }
    $load_more = 0;
    $list_customer_order = $core->getListCustomerOrderFilterByCustomer($zen_order_id, $order_by, $where, 1, $load_more, $total_result, 0);
    if ($list_customer_order) {

        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Ha Nguyen")
                ->setLastModifiedBy("Ha Nguyen")
                ->setTitle("zen's order")
                ->setSubject("zen's order")
                ->setDescription("zen's order, generated using PHP classes.")
                ->setKeywords("zen's order")
                ->setCategory("zen's order");
        $excel = $objPHPExcel->setActiveSheetIndex(0);
        $excel->setCellValue('A1', 'Start time')
                ->setCellValue('B1', $old_start_time);
        $excel->getStyle('A1:A2')->getFont()->setBold(true);
        $excel->setCellValue('A2', 'End time')
                ->setCellValue('B2', $old_end_time);
        $excel->setCellValue('A3', 'STT')
                ->setCellValue('B3', 'Tên FB')
                ->setCellValue('C3', 'Phone')
                ->setCellValue('D3', 'Mã SP')
                ->setCellValue('E3', 'Size')
                ->setCellValue('F3', 'Số lượng')
                ->setCellValue('G3', 'Màu')
                ->setCellValue('H3', 'Ảnh')
                ->setCellValue('I3', 'Order status');

        $excel->setCellValue('J3', 'Thời gian');

        $excel->setCellValue('K3', 'Ghi chú sản phẩm');

        if ($hidden_group_3 == 0) {
            $excel->setCellValue('L3', 'Giá(x1000 VNĐ)');
        }
        if ($hidden_group_2 == 0) {
            $excel->setCellValue('M3', 'Giá AT');
        }
        if ($hidden_group_1 == 0) {
            $excel->setCellValue('N3', 'Giá PT');
        }
        if ($hidden_group_2 == 0) {
            $excel ->setCellValue('O3', 'Tổng giá AT');
        }
        if ($hidden_group_1 == 0) {
            $excel->setCellValue('P3', 'Tổng giá PT');
        }

        if ($hidden_group_3 == 0) {
            $excel->setCellValue('Q3', 'Tổng tiền(x1000 VNĐ)')
                    ->setCellValue('R3', 'Tổng cọc(x1000 VNĐ)')
                    ->setCellValue('S3', 'Thiếu(x1000 VNĐ)')
                    ->setCellValue('T3', 'Thừa(x1000 VNĐ)');

        }
        $excel->setCellValue('U3', 'Ghi chú đơn hàng');
        if ($hidden_group_4 == 0) {
            $excel->setCellValue('V3', 'Địa chỉ')
                    ->setCellValue('W3', 'Tỉnh')
                    ->setCellValue('X3', 'Tên thật')
                    ->setCellValue('Y3', 'Tài khoản bank');
        }
        $excel->getStyle('A3:Y3')->getFont()->setBold(true);

        for ($i = 1; $i < 26; $i++) {
            if ($i != 7) {
                //bo qua cot image
                $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true);
            }
            //$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(12);
        }

        $excel->getStyle('A3:Y3')->getFont()->setName('Arial');
        if ($is_group_customer == 0) {
            //sắp xếp theo ngày ORDER hoặc theo mã sp: không gom nhóm khách được

            $count = 4;
            $stt = 0;


            foreach ($list_customer_order as $order) {
                $stt++;
                $excel->getStyle('A' . $count . ':Y' . $count)->getFont()->setName('Arial');
                $date_status = '';
                $status = '';
                switch ($order->order_status) {
                    case 0:
                        //store
                        $status.='Store';
                        $date_status = $core->changeDateMysqlToShow($order->store_date);
                        break;
                    case 1:
                        //online
                        $status.='Online';
                        $date_status = $core->changeDateMysqlToShow($order->online_date);
                        break;
                    case 2:
                        //hàng có sẵn
                        $status.='Hàng có sẵn';
                        break;
                    case 3:
                        //đã nhận hàng
                        $status.='Đã nhận hàng';
                        $date_status = $core->changeDateMysqlToShow($order->received_date);
                        break;
                    case 4:
                        //đang shipping
                        $status.='Đang shipping';
                        break;
                    case 5:
                        //khách đã nhận
                        $status.='Khách đã nhận';
                        $date_status = $core->changeDateMysqlToShow($order->saled_date);
                        break;
                    case 6:
                        //hết hàng
                        $status.='Hết hàng';
                        break;
                    case 7:
                        //ORDER
                        $status.='ORDER';
                        $date_status = $core->changeDateMysqlToShow($order->customer_order_date);
                        break;
                    case 8:
                        //chưa chắc chắn
                        $status.='Chưa chắc chắn';
                        break;
                }
                if ($order->province == 1)
                    $province = "Ở tỉnh";
                else
                    $province = "Ở HN";
                $color_photo_name = $order->product_color . "_" . $order->product_code . "_" . $order->manufacture;
                $color_photo_name = $core->convert_string_friendly($color_photo_name) . ".jpg";
                $path_color_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . "thumb_extra_photo" . DS . $color_photo_name;
                if (!file_exists($path_color_photo)) {
                    $path_color_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $order->main_photo;
                    if (!file_exists($path_color_photo)) {
                        $path_color_photo = '';
                    }
                }


                $excel->setCellValue('A' . $count, $stt)
                        ->setCellValue('B' . $count, $order->facebook_name)
                        ->setCellValue('C' . $count, $order->phone)
                        ->setCellValue('D' . $count, $order->product_code)
                        ->setCellValue('E' . $count, $order->product_size)
                        ->setCellValue('F' . $count, $order->product_num)
                        ->setCellValue('G' . $count, $order->product_color);
                if ($path_color_photo != '') {
                    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
                    $objPHPExcel->getActiveSheet()->getRowDimension($count)->setRowHeight(75);
                    $objDrawing = new PHPExcel_Worksheet_Drawing();
                    $objDrawing->setName('image');
                    $objDrawing->setDescription('image');
                    $objDrawing->setPath($path_color_photo);
                    $objDrawing->setHeight(120);
                    $objDrawing->setWidth(80);
                    $objDrawing->setCoordinates('H' . $count);
                    //$objDrawing->setOffsetX(10);
                    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                }
                $excel->setCellValue('I' . $count, $status);

                $excel->setCellValue('J' . $count, $date_status);

                $excel->setCellValue('K' . $count, $order->description);
                if ($hidden_group_3 == 0) {
                    $excel->setCellValue('L' . $count, $order->product_price / 1000);
                }
                if ($hidden_group_2 == 0) {
                    $excel->setCellValue('M' . $count, $order->stamp_price);
                }
                if ($hidden_group_1 == 0) {
                    $excel->setCellValue('N' . $count, $order->store_price);
                }
                if ($hidden_group_2 == 0) {
                    $excel->setCellValue('O' . $count, $order->product_num * $order->stamp_price);
                }
                if ($hidden_group_1 == 0) {
                    $excel->setCellValue('P' . $count, $order->product_num * $order->store_price);
                }

                if ($hidden_group_3 == 0) {
                    $excel->setCellValue('Q' . $count, $order->product_num * $order->product_price / 1000)
                            ->setCellValue('R' . $count, $order->total_payment / 1000)
                            ->setCellValue('S' . $count, '')
                            ->setCellValue('T' . $count, '');

                }
                $excel->setCellValue('U' . $count, $order->order_description);
                if ($hidden_group_4 == 0) {
                    $excel->setCellValue('V' . $count, $order->address)
                            ->setCellValue('W' . $count, $province)
                            ->setCellValue('X' . $count, $order->name)
                            ->setCellValue('Y' . $count, $order->bank_account);
                }
                $count++;
            }
        } else {
            $count = 4;
            $stt = 0;
            $customer_order_id = 0;
            foreach ($list_customer_order as $order) {
                $excel->getStyle('A' . $count . ':T' . $count)->getFont()->setName('Arial');
                $date_status = '';
                $status = '';
                switch ($order->order_status) {
                    case 0:
                        //store
                        $status.='Store';
                        $date_status = $core->changeDateMysqlToShow($order->store_date);
                        break;
                    case 1:
                        //online
                        $status.='Online';
                        $date_status = $core->changeDateMysqlToShow($order->online_date);
                        break;
                    case 2:
                        //hàng có sẵn
                        $status.='Hàng có sẵn';
                        break;
                    case 3:
                        //đã nhận hàng
                        $status.='Đã nhận hàng';
                        $date_status = $core->changeDateMysqlToShow($order->received_date);
                        break;
                    case 4:
                        //đang shipping
                        $status.='Đang shipping';
                        break;
                    case 5:
                        //khách đã nhận
                        $status.='Khách đã nhận';
                        $date_status = $core->changeDateMysqlToShow($order->saled_date);
                        break;
                    case 6:
                        //hết hàng
                        $status.='Hết hàng';
                        break;
                    case 7:
                        //ORDER
                        $status.='ORDER';
                        $date_status = $core->changeDateMysqlToShow($order->customer_order_date);
                        break;
                    case 8:
                        //chưa chắc chắn
                        $status.='Chưa chắc chắn';
                        break;
                }
                $color_photo_name = $order->product_color . "_" . $order->product_code . "_" . $order->manufacture;
                $color_photo_name = $core->convert_string_friendly($color_photo_name) . ".jpg";
                $path_color_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . "thumb_extra_photo" . DS . $color_photo_name;
                if (!file_exists($path_color_photo)) {
                    $path_color_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $order->main_photo;
                    if (!file_exists($path_color_photo)) {
                        $path_color_photo = '';
                    }
                }
                if ($customer_order_id != $order->customer_order_id) {
                    $stt++;
                    $customer_order_id = $order->customer_order_id;
                    if ($order->province == 1)
                        $province = "Ở tỉnh";
                    else
                        $province = "Ở HN";
                    if ($order->total_current_money > 0) {
                        $excess_cash = $order->total_current_money / 1000;
                        $debit = 0;
                    } else {
                        $excess_cash = 0;
                        $debit = $order->total_current_money / 1000;
                    }

                    $excel->setCellValue('A' . $count, $stt)
                            ->setCellValue('B' . $count, $order->facebook_name)
                            ->setCellValue('C' . $count, $order->phone)
                            ->setCellValue('D' . $count, $order->product_code)
                            ->setCellValue('E' . $count, $order->product_size)
                            ->setCellValue('F' . $count, $order->product_num)
                            ->setCellValue('G' . $count, $order->product_color);
                    if ($path_color_photo != '') {
                        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
                        $objPHPExcel->getActiveSheet()->getRowDimension($count)->setRowHeight(75);
                        $objDrawing = new PHPExcel_Worksheet_Drawing();
                        $objDrawing->setName('image');
                        $objDrawing->setDescription('image');
                        $objDrawing->setPath($path_color_photo);
                        $objDrawing->setHeight(120);
                        $objDrawing->setWidth(80);
                        $objDrawing->setCoordinates('H' . $count);
                        //$objDrawing->setOffsetX(10);
                        $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                    }
                    $excel->setCellValue('I' . $count, $status);
                    $excel->setCellValue('J' . $count, $date_status);
                    $excel->setCellValue('K' . $count, $order->description);
                    if ($hidden_group_3 == 0) {
                        $excel->setCellValue('L' . $count, $order->product_price / 1000);
                    }
                    if ($hidden_group_2 == 0) {
                        $excel->setCellValue('M' . $count, $order->stamp_price);
                    }
                    if ($hidden_group_1 == 0) {
                        $excel->setCellValue('N' . $count, $order->store_price);
                    }
                    if ($hidden_group_2 == 0) {
                        $excel->setCellValue('O' . $count, $order->total_at);
                    }
                    if ($hidden_group_1 == 0) {
                        $excel->setCellValue('P' . $count, $order->total_pt);
                    }

                    if ($hidden_group_3 == 0) {
                        $excel->setCellValue('Q' . $count, $order->total_order_money / 1000)
                                ->setCellValue('R' . $count, $order->total_payment / 1000)
                                ->setCellValue('S' . $count, $debit)
                                ->setCellValue('T' . $count, $excess_cash)
                                ;
                    }
                    $excel->setCellValue('U' . $count, $order->order_description);
                    if ($hidden_group_4 == 0) {
                        $excel->setCellValue('V' . $count, $order->address)
                                ->setCellValue('W' . $count, $province)
                                ->setCellValue('X' . $count, $order->name)
                                ->setCellValue('Y' . $count, $order->bank_account);
                    }
                    $merge = $count + $order->total_product;


//                    $excel->mergeCells('A' . $count.':A'.$merge)
//                            ->mergeCells('B' . $count.':B'.$merge)
//                            ->mergeCells('C' . $count.':C'.$merge)
//                            ->mergeCells('K' . $count.':K'.$merge)
//                            ->mergeCells('L' . $count.':L'.$merge)
//                            ->mergeCells('M' . $count.':M'.$merge)
//                            ->mergeCells('N' . $count.':N'.$merge)
//                            ->mergeCells('O' . $count.':O'.$merge)
//                            ->mergeCells('P' . $count.':P'.$merge)
//                            ->mergeCells('Q' . $count.':Q'.$merge)
//                            ->mergeCells('R' . $count.':R'.$merge)
//                            ->mergeCells('S' . $count.':S'.$merge);
                } else {

                    $excel->setCellValue('D' . $count, $order->product_code)
                            ->setCellValue('E' . $count, $order->product_size)
                            ->setCellValue('F' . $count, $order->product_num)
                            ->setCellValue('G' . $count, $order->product_color);
                    if ($path_color_photo != '') {
                        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
                        $objPHPExcel->getActiveSheet()->getRowDimension($count)->setRowHeight(75);
                        $objDrawing = new PHPExcel_Worksheet_Drawing();
                        $objDrawing->setName('image');
                        $objDrawing->setDescription('image');
                        $objDrawing->setPath($path_color_photo);
                        $objDrawing->setHeight(120);
                        $objDrawing->setWidth(80);
                        $objDrawing->setCoordinates('H' . $count);
                        //$objDrawing->setOffsetX(10);
                        $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                    }
                    $excel->setCellValue('I' . $count, $status);

                    $excel->setCellValue('J' . $count, $date_status);

                    $excel->setCellValue('K' . $count, $order->description);
                    if ($hidden_group_3 == 0) {
                        $excel->setCellValue('L' . $count, $order->product_price / 1000);
                    }
                    if ($hidden_group_2 == 0) {
                        $excel->setCellValue('M' . $count, $order->stamp_price);

                    }
                    if ($hidden_group_1 == 0) {
                        $excel->setCellValue('N' . $count, $order->store_price);

                    }
                }


                $count++;
            }
        }
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Zen product');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('../download/zen_order.xls');
        echo json_encode(array('type' => 0, 'url_excel' => "download/zen_order.xls"));
        die;
    } else {
        echo json_encode(array('type' => 1, 'msg' => "Không có dữ liệu."));
        die;
    }
} else {
    echo json_encode(array('type' => 1, 'msg' => "Đợt hàng không tồn tại."));
    die;
}

